'use strict'

module.exports = options => {
  const { ctx } = options

  /**
   * 默认校验规则集
   */
  const defaultRules = {
    number: value => !isNaN(Number(value))
  }

  /**
   * 校验参数
   * @param {object} validateRules 传入的校验条件
   */
  const validate = (validateRules = {}) => {
    const { method, query, body } = ctx.request
    let validateParams
    switch (method) {
      case 'GET':
        validateParams = query
        break;
      case 'POST':
      case 'DELETE':
        validateParams = body
        break;
      default:
        validateParams = {}
        break;
    }

    for (const key in validateRules) {
      if (Object.hasOwnProperty.call(validateRules, key)) {
        const validkey = validateRules[key] // 校验规则
        const validVal = validateParams[key] // 校验值

        if (defaultRules[validkey]) {
          if(!defaultRules[validkey](validVal)) {
            throw new Error(`parameter ${key} should be the type of ${validkey}`)
          }
        } else {
          throw new Error(`${validkey} is not defined`)
        }
      }
    }
  }

  return validate
}